<?php
namespace control;
/*
*试题管理类
*/

class topicManagementClass extends adIndexClass
{
    private const page = 'topicManagement';
    private const table = 'topic_library_detail';
    private const title = '试题管理';
    public array $topicTypeOption = ['单选题','多选题','判断题','主观题'];
    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            select(array("name" => "type","title" => L('topic.table.topicType'), "option" => explode('，', para('topicLibraryOption')))).
            text(array("name" => "name", "title" => L('topic.table.topicName'))) .
            select(array("name" => "topicType","title" => L('topic.table.questionsType'), "option" => $this->topicTypeOption)).
            text(array("name" => "title", "title" => L('topic.table.stem'))) .
            select(array("name" => "state", "title" => L('trainingPlan.table.state'), "option" => ['启用', '停用']));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "title" => $this->post('title'),//题干
            "name" => $this->post('name'),//计划名称
        );
        //全等查询数组
        $equal = array(
            "b.state" => $this->post('state'),//状态
            "a.type" => $this->post('type'),//题库分类
            "b.topicType" => $this->post('topicType'),//试题类型
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => "topic_library as a join ".self::table." as b on a.id = b.orderId", 'field'=>" b.*,a.type,a.name","where" => $where, "order" => "b.time desc", ));
        //获取表头
        $checkAll = $this->checkAll("detailForm", "mxId");
        $tr[] = array($checkAll, L('topic.table.topicType'), L('topic.table.topicName'), L('topic.table.questionsType'),L('topic.table.stem'),L('trainingPlan.table.state'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
                "detail" => array("title" => L('topic.table.topic_library_detail'), "click" => "newIframe('" . L('topic.table.topic_library_detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );

            $tr[] = array($this->dominate($dominate), $array['type'], $array['name'], $array['topicType'],html_entity_decode($array['title'],ENT_QUOTES), $array['state']);
        }
        //控件
        $button = "";

        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('department.button.delete')."</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('topicLibrary','stateSwitch',{type:'启用',classify:'topic'})\" class='spanButton'>".L('topic.table.enable')."</span>\n";
            $button .= "<span onclick=\"layer('topicLibrary','stateSwitch',{type:'停用',classify:'topic'})\" class='spanButton'>".L('topic.table.unenable')."</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='detailForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html =  L('topic.table.bo_library');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            //题库信息
            $library = query('topic_library'," id = '$info[orderId]'");

            $button = [];
            if ($this->power(self::page, "edit")) {
                $fun = '';
                if ($info['topicType'] =='单选题'){
                    $fun = 'addSingle';
                }elseif($info['topicType'] =='多选题'){
                    $fun = 'addMultiple';
                }elseif ($info['topicType'] =='判断题'){
                    $fun = 'addJudgment';
                }elseif ($info['topicType'] =='主观题'){
                    $fun = 'addMainTopic';
                }
                //按钮
                $button[] = [
                    "name" =>L('department.button.editor'),
                    "type" => "点击事件",
                    "title" => L('department.button.editor'),
                    'fun'=>"layer('topicLibrary','$fun',{mainId:'{$info['orderId']}',source:'".self::page."',id:'{$info['id']}'})",
                    'style' => 'li-btn-blue-bg',
                ];
                if ($info['state'] =='启用'){
                    //按钮
                    $button[] = [
                        "name" =>L('topic.table.unenable'),
                        "type" => "点击事件",
                        "title" =>L('topic.table.unenable'),
                        'fun'=>"layer('topicLibrary','stateSwitch',{tid:'{$info['id']}',classify:'topic',type:'停用'})",
                    ];
                }else{
                    //按钮
                    $button[] = [
                        "name" => L('topic.table.enable'),
                        "type" => "点击事件",
                        "title" =>L('topic.table.enable'),
                        'fun'=>"layer('topicLibrary','stateSwitch',{tid:'{$info['id']}',classify:'topic',type:'启用'})",
                    ];
                }

            }
            if ($this->power(self::page,'del')){
                //按钮
                $button[] = [
                    "name" => L('department.button.delete'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $obj = new topicLibraryClass();
            $result = $obj->showItemAndAnswer($info);
            $itemText = $result['itemText'];
            $answerText = $result['answerText'];
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('topic.table.questionsType') => $info['topicType'],
                        L('topic.table.score')=> $info['score'],
                    ),
                    array(
                        L('topic.table.stem') => $info['title'],
                    ),
                    array(
                        L('topic.table.optionText') =>$itemText,
                    ),
                    array(
                        L('topic.table.answer') =>$answerText,
                    ),
                ),
                L('recruitment.table.state')=>array(
                    array(
                        L('topic.table.orderNo')=>$library['orderNo'],
                        L('topic.table.topicName') => $library['name'],
                        L('topic.table.topicType') => $library['type'],
                    ),
                    array(
                        L('department.table.creator') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                        L('trainingPlan.table.state') => $info['state'],
                    ),
                )
            ));


            //生成页面
            $html = $this->tab($data)."<form name='detailForm'>". hidden(array('name' => 'tid', 'value' => $info['id'])) . "</form>";
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('topic.table.del_title');
                $title = 'topicLibraryDelete';
                $function = 'delete';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] =str_replace(['{{msg}}'],[$msg],L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('mxId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($info['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn =L('topic.table.del_warn');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn =  L('job.other.delete_success');
                    $x++;
                }

                $text .= str_replace(['{{title}}','{{id}}'],[$info['title'],$info['id']],L('topic.table.que_del_text')). $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('topic.table.topic_del_log')). $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('topic.table.topic_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

